package com.skyline.courier.rpc;

import net.sf.cglib.proxy.Enhancer;

import com.skyline.courier.net.Client;
import com.skyline.courier.rpc.exception.RpcGenerateException;

public class ServiceAccessorFactory {
	private Client client;

	@SuppressWarnings("unchecked")
	public <T> T createService(Class<T> clazz) throws Exception {
		ServiceAccessorInterceptor interceptor = newServiceAccessorInterceptor(clazz);
		T instance = (T) Enhancer.create(clazz, interceptor);
		return instance;
	}

	/**
	 * 创建ServiceProxyInterceptor实例
	 * 
	 * @return
	 * @throws RpcGenerateException
	 */
	private ServiceAccessorInterceptor newServiceAccessorInterceptor(Class<?> clazz) throws RpcGenerateException {
		if (client == null) {
			throw new RpcGenerateException("创建RPC失败：未指定远程服务连接器");
		}
		return new ServiceAccessorInterceptor(clazz, client);
	}

	public void setConnector(Client client) {
		this.client = client;
	}
	
	@Override
	protected void finalize() throws Throwable {
		client.close();
		super.finalize();
	}
}
